<template>
  <!-- <i :class="['iconfont', type]" v-on="$listeners" v-bind="$attrs" /> -->
  <svg :style="style" aria-hidden="true" ref="svg" :class="svgClass" v-on="$listeners" v-bind="$attrs">
    <use :xlink:href="symbolId" />
  </svg>
</template>

<script>
/**
 * @module SIcon
 * @vue-prop {String} type icon的svg文件名字（icon名称在src/assets/icons）
 * 例如：src/assets/icons/graph/xxx.svg 需要加上icons下的文件夹名称"graph-",type="graph-xxx"，否则直接传入type="xxx"
 * @vue-computed  {String} symbolI  icon的svg文件路径
 * @vue-computed {String} svgClass icon的svg的class类名
 * @vue-prop {Number} size 图标大小
 * @vue-prop {String} prefix vite.config.js中配置的svg-sprite-loader的symbolId前缀 默认为icon
 * @example <svg-icon type="import" size="12" />
 */
export default {
  name: "SIcon",
  props: {
    prefix: {
      type: String,
      default: "icon",
    },
    size: [String, Number],
    type: {
      type: String,
      default: "",
    },
    hoverPath: {
      type: String,
      default: "_act",
    },
    useHover: {
      type: Boolean,
      default: false,
    },
    isActive: {
      type: Boolean,
      default: false,
    },
    className: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      isAct: false,
    };
  },
  computed: {
    symbolId() {
      return this.isAct || this.isActive
        ? `#${this.prefix}-${this.type}${this.hoverPath}`
        : `#${this.prefix}-${this.type}`;
    },
    svgClass() {
      let classArr = ["svg-icon"];
      if (this.className) {
        classArr.push(this.className);
        return classArr;
      }
      return classArr;
    },
    style() {
      return this.size ? { fontSize: this.size + "px" } : {};
    },
  },
  mounted() {
    if (this.useHover) {
      this.$refs.svg.addEventListener("mouseover", this.showAct);
      this.$refs.svg.addEventListener("mouseout", this.hideAct);
    }
  },
  beforeDestroy() {
    if (this.useHover) {
      this.$refs.svg.removeEventListener("mouseover", this.showAct);
      this.$refs.svg.removeEventListener("mouseout", this.hideAct);
    }
  },
  methods: {
    showAct() {
      if (this.isAct) return;
      this.isAct = true;
    },
    hideAct() {
      if (!this.isAct) return;
      this.isAct = false;
    },
  },
};
</script>
<style>
.svg-icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor !important;
  overflow: hidden;
  color: var(--theme-color-text-low);
}
</style>
